package com.zhengtoudai.ui.activity;

import android.app.DatePickerDialog;
import android.os.Bundle;
import android.support.v4.content.ContextCompat;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.widget.DatePicker;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.TextView;

import com.zhengtoudai.R;
import com.zhengtoudai.base.App;
import com.zhengtoudai.base.BaseActivity;
import com.zhengtoudai.http.HttpUtil;
import com.zhengtoudai.injector.component.DaggerActivityComponent;
import com.zhengtoudai.injector.module.ActivityModule;
import com.zhengtoudai.ui.adapter.FundRecordAdapter;
import com.zhengtoudai.ui.adapter.PopupRecycleAdapter;
import com.zhengtoudai.ui.bean.AccountLog;
import com.zhengtoudai.ui.presenter.AccountLogPresenterImpl;
import com.zhengtoudai.ui.view.AccountLogView;
import com.zhengtoudai.util.AbToastUtil;
import com.zhengtoudai.util.DensityUtil;
import com.zhengtoudai.util.Tool;
import com.zhengtoudai.view.recyclerview.RecyclerViewAdapter;
import com.zhengtoudai.view.swipetoloadlayout.base.OnLoadMoreListener;
import com.zhengtoudai.view.swipetoloadlayout.base.OnRefreshListener;
import com.zhengtoudai.view.swipetoloadlayout.base.SwipeToLoadLayout;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.inject.Inject;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * 资金记录
 */
public class FundRecordActivity extends BaseActivity implements OnRefreshListener, OnLoadMoreListener, AccountLogView {

    @Bind(R.id.tv_start_time)
    TextView mTvStartTime;
    @Bind(R.id.tv_end_time)
    TextView mTvEndTime;
    @Bind(R.id.tv_type)
    TextView mTvType;
    @Bind(R.id.tv_query)
    TextView mTvQuery;
    @Bind(R.id.swipe_target)
    RecyclerView mSwipeTarget;
    @Bind(R.id.refresh)
    SwipeToLoadLayout mRefresh;
    @Bind(R.id.ll_filter)
    LinearLayout mLlFilter;
    @Bind(R.id.activity_fund_record)
    LinearLayout mActivityFundRecord;
    private FundRecordAdapter mAdapter;
    private DatePickerDialog startDateDialog;
    private DatePickerDialog endDateDialog;
    private String startDate;
    private String endDate;
    private String tradeCode;
    private int numPerPage = 10, pageNum = 1;

    private AccountLog result;

    private PopupWindow popupWindow;

    private List<AccountLog.ResultEntity.TradeCode> tradeCodes;

    private PopupRecycleAdapter mPopupRecycleAdapter;

    @Inject
    AccountLogPresenterImpl mPresenter;

    @Inject
    LayoutInflater mInflater;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_fund_record);
        ButterKnife.bind(this);
    }

    @Override
    protected void initTitle() {
        titleUtil.setTitle("资金记录");
        DaggerActivityComponent.builder().appComponent(App.mApp.getAppComponent())
                .activityModule(new ActivityModule(this))
                .build()
                .inject(this);
        mPresenter.attachView(this);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        mPresenter.detachView();
    }

    @Override
    protected void initView() {
        mRefresh.setOnRefreshListener(this);
        mRefresh.setOnLoadMoreListener(this);
        mSwipeTarget.setLayoutManager(new LinearLayoutManager(context));
        mAdapter = new FundRecordAdapter();
        mSwipeTarget.setAdapter(mAdapter);

        tradeCodes=new ArrayList<>();
        accountLog(false);
        autoLoading(mRefresh,mSwipeTarget);

    }

    @Override
    public boolean dispatchTouchEvent(MotionEvent ev) {
        if (popupWindow!=null&&popupWindow.isShowing()){
            popupWindow.dismiss();
            return true;
        }
        return super.dispatchTouchEvent(ev);
    }

    @Override
    public void onBackPressed() {
        if (popupWindow!=null&&popupWindow.isShowing()){
            popupWindow.dismiss();
        }else{
            super.onBackPressed();
        }
    }

    /**
     * 是否上啦加载，不是的话清空数据
     *
     * @param isLoadMore
     */
    private void accountLog(boolean isLoadMore) {
        if (!isLoadMore) {
            mAdapter.clearData();
        }

        Map<String, String> params = new HashMap<>();
        params.put("numPerPage", numPerPage + "");
        params.put("pageNum", pageNum + "");
        if (startDate != null) {
            params.put("beginTime", startDate);
        }
        if (endDate != null) {
            params.put("endTime", endDate);
        }
        if (tradeCode != null) {
            params.put("tradeCode", tradeCode);
        }
        mPresenter.accountLog(params);
    }


    @OnClick({R.id.tv_start_time, R.id.tv_end_time, R.id.tv_type, R.id.tv_query})
    public void onClick(View view) {
        if (Tool.isFastDoubleClick()) return;
        switch (view.getId()) {
            case R.id.tv_start_time:
                if (startDateDialog == null) {
                    int year, month, day;
                    if (TextUtils.isEmpty(startDate)) {
                        Calendar calendar = Calendar.getInstance();
                        year = calendar.get(Calendar.YEAR);
                        month = calendar.get(Calendar.MONTH);
                        day = calendar.get(Calendar.DAY_OF_MONTH);

                    } else {
                        String[] starts = startDate.split("-");
                        year = Integer.parseInt(starts[0]);
                        month = Integer.parseInt(starts[1]);
                        day = Integer.parseInt(starts[2]);
                    }
                    startDateDialog = new DatePickerDialog(this, new DatePickerDialog.OnDateSetListener() {
                        @Override
                        public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
                            if (monthOfYear < 11) {
                                monthOfYear++;
                            } else {
                                year++;
                                monthOfYear = 1;
                            }
                            String monthStr=monthOfYear<10?"0"+monthOfYear:monthOfYear+"";

                            String dayStr=dayOfMonth<10?"0"+dayOfMonth:""+dayOfMonth;

                            startDate = year + "-" + monthStr + "-" + dayStr;
                            mTvStartTime.setText(startDate);
                        }
                    }, year, month, day);
                }
                startDateDialog.show();

                break;
            case R.id.tv_end_time:
                if (endDateDialog == null) {
                    int year, month, day;
                    if (TextUtils.isEmpty(endDate)) {
                        Calendar calendar = Calendar.getInstance();
                        year = calendar.get(Calendar.YEAR);
                        month = calendar.get(Calendar.MONTH);
                        day = calendar.get(Calendar.DAY_OF_MONTH);

                    } else {
                        String[] starts = endDate.split("-");
                        year = Integer.parseInt(starts[0]);
                        month = Integer.parseInt(starts[1]);
                        day = Integer.parseInt(starts[2]);
                    }
                    endDateDialog = new DatePickerDialog(this, new DatePickerDialog.OnDateSetListener() {
                        @Override
                        public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
                            if (monthOfYear < 11) {
                                monthOfYear++;
                            } else {
                                year++;
                                monthOfYear = 1;
                            }
                            String monthStr=monthOfYear<10?"0"+monthOfYear:monthOfYear+"";

                            String dayStr=dayOfMonth<10?"0"+dayOfMonth:""+dayOfMonth;

                            endDate = year + "-" + monthStr + "-" + dayStr;

                            mTvEndTime.setText(endDate);
                        }
                    }, year, month, day);

                }
                endDateDialog.show();
                break;
            case R.id.tv_type:
                if (result == null || tradeCodes == null) {
                   /* AbToastUtil.showToast(context, "正在获取数据中...");
                    accountLog(false);*/
                    return;
                }
                if (popupWindow == null) {
                    initPopupWindow();
                }
                if (popupWindow.isShowing()) {
                    popupWindow.dismiss();
                } else {
                    popupWindow.showAsDropDown(mLlFilter);
                }
                break;
            case R.id.tv_query:
                accountLog(false);
                break;
        }
    }


    private void initPopupWindow() {
        popupWindow = new PopupWindow(mLlFilter.getWidth(), DensityUtil.dip2px(context,200));
        View view = mInflater.inflate(R.layout.popupwindow_account_log_list_item, null);
        RecyclerView popupRecycler = (RecyclerView) view.findViewById(R.id.popup_recycler);
        popupRecycler.setLayoutManager(new LinearLayoutManager(this));
        mPopupRecycleAdapter = new PopupRecycleAdapter();
        mPopupRecycleAdapter.addData(tradeCodes);
        popupRecycler.setAdapter(mPopupRecycleAdapter);
        mPopupRecycleAdapter.setOnItemClickListener(new RecyclerViewAdapter.OnItemClick() {
            @Override
            public void onItemClick(View view, int position) {
                popupWindow.dismiss();
                mPopupRecycleAdapter.setCheckPosition(position);
                mTvType.setText(mPopupRecycleAdapter.getData().get(position).getValue());
                tradeCode = mPopupRecycleAdapter.getData().get(position).getKey();
            }
        });
        popupWindow.setContentView(view);
        popupWindow.setBackgroundDrawable(ContextCompat.getDrawable(context, R.drawable.shape_bottom_circle));
    }


    @Override
    public void onLoadMore() {
        if (result != null && result.getResult().getPageInfo() != null) {
            if (pageNum < result.getResult().getPageInfo().getTotalNum()) {
                pageNum++;
                accountLog(true);
            } else {
                AbToastUtil.showToast(context, "已无更多数据");
                mRefresh.setLoadingMore(false);
            }
        } else {
            AbToastUtil.showToast(context, "已无更多数据");
            mRefresh.setLoadingMore(false);
        }

    }

    @Override
    public void onRefresh() {

        pageNum = 1;
        mTvStartTime.setText("开始时间");
        startDate = null;
        mTvEndTime.setText("结束时间");
        endDate = null;
        mTvType.setText("全部");
        tradeCode = null;
        if (mPopupRecycleAdapter != null) {
            mPopupRecycleAdapter.setCheckPosition(-1);
        }
        accountLog(false);
    }

    @Override
    public void showDialog() {
        showProgressDialog("正在获取资金记录...");
    }

    @Override
    public void onFailure(Throwable e) {
        dismissProgressDialog();
        onComplete(mRefresh);
        HttpUtil.disposeOnFailure(this, e);
    }

    @Override
    public void onResult(AccountLog result) {
        this.result = result;
        if (result.getResult().getList().size() == 0) {
            AbToastUtil.showToast(context, "暂无资金记录");
        } else {

            mAdapter.addData(result.getResult().getList());

            if (result.getResult().getTradeCodes()!=null&&tradeCodes.size()==0){
                tradeCodes.addAll(result.getResult().getTradeCodes());
            }
        }
    }

    @Override
    public void dismissDialog() {
        dismissProgressDialog();
        onComplete(mRefresh);
    }
}
